import { Device, GatewayType } from "@/api/interface/iot";
import {
	addRule,
	addRuleProcessor,
	delRule,
	disableRule,
	enableRule,
	getRuleList,
	getRuleProcessorList,
	modRule,
	modRuleProcessor
} from "@/api/modules/iot/rule";
import Empty from "@/components/Empty";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import OnlineStatus from "@/components/Sansan/Status/OnlineStatus";
import { MessageType } from "@/enums/messageEnum";
import { RouterPath } from "@/enums/routerPath";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import { useRoute, useRouter } from "vue-router";
import BasicDialog from "./components/detailDialog";
import SaveTorule from "./components/copyRule";
import "./rule.scss";
import { gotoPage } from "@/utils/routerUtil";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const router = useRouter();
		const route = useRoute();
		const initParam = reactive<Device.ReqRule>({});

		const dataCallback = (data: any) => {
			data.records.map((item: any) => {
				item.status = item.status + "";
				return item;
			});
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current || 1,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			// return { result: { records: [{}] } };
			return getRuleList(params);
		};
		const buttonsList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			buttonsList.value = await useAuthButtons();
		});
		const detailDialog = reactive({
			title: proxy?.$t("rulelinks.dialog_title.add"),
			detail: {} as any,
			visible: false
		});
		const clickBtn = async (fn: string, row?: any) => {
			let selected: any[] = row ? row.selectList || [row] : [];
			switch (fn) {
				case "details":
					if (selected.length != 1) {
						showMsg(proxy?.$t("rulelinks.msg.details"), MessageType.warning);
						return;
					}
					router.push({
						path: RouterPath.ruleDetail,
						query: { id: selected[0].id, type: selected[0].deviceType, menuId: route.meta.id as string }
					});
					break;
				case "mod":
					if (!selected.length) {
						showMsg(proxy?.$t("rulelinks.msg.mod"), MessageType.warning);
						return;
					}
					detailDialog.detail = { ...selected[0] };
					detailDialog.visible = true;
					break;
				case "add":
					detailDialog.detail = {};
					detailDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("rulelinks.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("rulelinks.confirm.del") }).then(async flag => {
						if (!flag) {
							return;
						}
						submitDel({ id: selected.map(item => item.id).join(",") });
					});
					break;
				case "enable":
					if (!selected.length) {
						showMsg(proxy?.$t("rulelinks.msg.enable"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("rulelinks.confirm.enable") }).then(flag => {
						if (!flag) {
							return;
						}
						submitEnable({ id: selected.map(item => item.id).join(",") });
					});
					break;
				case "disable":
					if (!selected.length) {
						showMsg(proxy?.$t("rulelinks.msg.disable"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("rulelinks.confirm.disable") }).then(flag => {
						if (!flag) {
							return;
						}
						submitDisable({ id: selected.map(item => item.id).join(",") });
					});
					break;
				case "copy":
					if (selected.length != 1) {
						showMsg(proxy?.$t("rulelinks.msg.copy"), MessageType.warning);
						return;
					}
					copyruleDialog.visible = true;
					copyruleDialog.formData = JSON.parse(JSON.stringify(selected[0]));
					// copyruleDialog.formData.id = selected[0].model;
					break;
			}
		};

		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "name", label: proxy?.$t("rulelinks.tablist_label.name"), search: { el: "input" } },
			{ prop: "deviceType", label: proxy?.$t("rulelinks.tablist_label.device_type"), search: { slot: {} } },
			{ prop: "descript", label: proxy?.$t("rulelinks.tablist_label.descript") },
			{ prop: "createTime", label: proxy?.$t("rulelinks.tablist_label.create_time") },
			{ prop: "operation", label: proxy?.$t("rulelinks.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const submitEnable = async (dataInfo: any) => {
			let { code, message } = await enableRule({ ...dataInfo });
			let ok = showTips(code, proxy?.$t("rulelinks.tips.enable"), message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.getTableList();
			}
		};
		const submitDisable = async (dataInfo: any) => {
			let { code, message } = await disableRule({ ...dataInfo });
			let ok = showTips(code, proxy?.$t("rulelinks.tips.disable"), message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.getTableList();
			}
		};
		const submitDel = async (dataInfo: any) => {
			let { code, message } = await delRule({ ...dataInfo });
			let ok = showTips(code, proxy?.$t("rulelinks.tips.del"), message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submitAdd = async () => {
			detailDialog.detail.name = detailDialog.detail.name || detailDialog.detail.model;
			let api = detailDialog.detail.id ? modRule : addRule;
			let { code, message } = await api(detailDialog.detail);
			let ok = showTips(code, proxy?.$t("rulelinks.tips.add"), message);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.getTableList();
				proTable.value.clearSelection();
			}
		};
		const copyruleDialog = reactive<any>({
			visible: false,
			formData: {}
		});
		const submitCopyrule = async (data: Device.ReqRule) => {
			let newrule = { ...copyruleDialog.formData };
			let id = newrule.id;
			newrule.name = data.name;
			delete newrule.id;
			let { code, message, result } = await addRule(newrule);
			let copyId = result;
			let ok = showTips(code, proxy?.$t("rulelinks.tips.copy"), message);
			if (ok) {
				copyruleDialog.visible = false;
				let res = await getRuleProcessorList({ ruleId: id });
				if (res.code == 200) {
					let list = res.result.records.reverse();
					let arr = JSON.parse(JSON.stringify(list)).map(async (item: any) => {
						item.ruleId = copyId;
						item.oldId = item.id;
						delete item.id;
						delete item.createTime;
						delete item.updateTime;
						let addRes = await addRuleProcessor(item);
						item.id = addRes?.result;
						return item;
					});
					arr = await Promise.all(arr);
					list.map(async (item: any, index: number) => {
						if (item.previous != "no") {
							arr[index].previous = arr.filter((findItem: any) => {
								return findItem.oldId == item.previous;
							})[0].id;
						}
						if (item.next != "no") {
							arr[index].next = arr.filter((findItem: any) => {
								return findItem.oldId == item.next;
							})[0].id;
						}
						await modRuleProcessor(arr[index]);
					});
				}
				proTable.value.getTableList();
			}
		};
		return () => {
			return (
				<div class="pt-2">
					<SaveTorule
						title={proxy?.$t("rulelinks.dialog_title.copy")}
						v-model:visible={copyruleDialog.visible}
						formData={copyruleDialog.formData}
						onSubmit={(data: Device.ReqRule) => submitCopyrule(data)}
					></SaveTorule>
					<BasicDialog
						width="600px"
						title={detailDialog.title}
						v-model:visible={detailDialog.visible}
						detail={detailDialog.detail}
						onSubmit={() => submitAdd()}
					></BasicDialog>
					<ProTable
						ref={proTable}
						title={buttonsList.value.length ? "" : proxy?.$t("rulelinks.tab_title.manage")}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
						searchCol={5}
						noList
						viewType="grid"
						gridSpan={8}
					>
						{{
							"search-status": () => {
								return (
									<el-select v-model={initParam.status} style="width:120px">
										<el-option label={proxy?.$t("rulelinks.status_option.all")} value=""></el-option>
										<el-option label={proxy?.$t("rulelinks.status_option.enable")} value="enable"></el-option>
										<el-option label={proxy?.$t("rulelinks.status_option.disable")} value="disable"></el-option>
									</el-select>
								);
							},
							"search-deviceType": () => {
								return (
									<el-select v-model={initParam.deviceType} style="width:100px">
										<el-option label={proxy?.$t("rulelinks.devtype_option.all")} value=""></el-option>
										<el-option label={proxy?.$t("rulelinks.devtype_option.device")} value={GatewayType.Device}></el-option>
										<el-option
											label={proxy?.$t("rulelinks.devtype_option.soft_gateway")}
											value={GatewayType.SoftGateway}
										></el-option>
										<el-option label={proxy?.$t("rulelinks.devtype_option.gateway")} value={GatewayType.Gateway}></el-option>
									</el-select>
								);
							},
							tableHeader: (scope: any) => {
								return buttonsList.value
									?.filter((item: any) => item.path != "mod")
									.map((item: any) => {
										return (
											<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
												<i class={`iconfont ${item.icon}`}></i>
												{item.menuName}
											</el-button>
										);
									});
							},
							cardBody: (scope: any) => {
								return (
									<div class="rule-card shadow-md">
										<div class="title flex justify-between">
											<div class="flex">
												<el-link
													title={proxy?.$t("rulelinks.card_link.title")}
													type="primary"
													onClick={() => clickBtn("details", scope.row)}
												>
													<div class="master-title">{scope.row.name || "变量转换规则"}</div>
												</el-link>
												<OnlineStatus
													v-model={scope.row.status}
													types={{ enable: "success", disable: "danger" }}
													labels={{
														enable: proxy?.$t("rulelinks.status.enable"),
														disable: proxy?.$t("rulelinks.status.disable")
													}}
													class="ml-4"
												/>
											</div>
											<div class="time">{dataFormat("datetime", scope.row.createTime)}</div>
										</div>
										<div class="body">
											<div class="block">
												<div class="flex">
													<div class="label">{proxy?.$t("rulelinks.card_label.name")}</div>
													<div class="text">{scope.row.name}</div>
												</div>
												<div class="flex">
													<div class="label">{proxy?.$t("rulelinks.card_label.productid")}</div>
													<div class="text">
														{scope.row.productId
															? proxy?.$t("rulelinks.card_text.productid")
															: scope.row.devSn
															? proxy?.$t("rulelinks.card_text.devsn")
															: "--"}
													</div>
												</div>
												<div class="flex">
													<div class="label">
														{scope.row.productId
															? proxy?.$t("rulelinks.card_text.product")
															: proxy?.$t("rulelinks.card_text.dev")}
													</div>
													<div class="text">
														<>
															{scope.row.productId?.split(",").map((item: string, i: number) => {
																return (
																	<>
																		{i > 0 ? <span class="p-1">, </span> : null}
																		<el-link type="primary" onClick={() => gotoPage(RouterPath.productDetail, { id: item })}>
																			{item}
																		</el-link>
																	</>
																);
															})}
															{scope.row.devSn?.split(",").map((item: string, i: number) => {
																return (
																	<>
																		{i > 0 ? <span class="p-1">, </span> : null}
																		<el-link type="primary" onClick={() => gotoPage(RouterPath.deviceDetail, { sn: item })}>
																			{item}
																		</el-link>
																	</>
																);
															})}
														</>
													</div>
												</div>
												<div class="flex">
													<div class="label">{proxy?.$t("rulelinks.card_label.creator")}</div>
													<div class="text">{scope.row.creator}</div>
												</div>
											</div>
										</div>
										<div class="footer flex justify-between">
											<el-button
												class="flex-1 iconfont icontrash-2"
												link
												type="danger"
												disabled={buttonsList.value.find((item: any) => item.path == "del") ? false : true}
												onClick={() => clickBtn("del", scope.row)}
											>
												{proxy?.$t("rulelinks.card_btn.del")}
											</el-button>
											<el-button
												class="flex-1 iconfont iconsettings"
												link
												title={proxy?.$t("rulelinks.card_btn.title")}
												type="primary"
												onClick={() => clickBtn("details", scope.row)}
											>
												{proxy?.$t("rulelinks.card_btn.details")}
											</el-button>
										</div>
									</div>
								);
							},
							status: (scope: any) => {
								return (
									<OnlineStatus
										v-model={scope.row.status}
										types={{ enable: "success", disable: "danger" }}
										labels={{ enable: proxy?.$t("rulelinks.status.enable"), disable: proxy?.$t("rulelinks.status.disable") }}
										class="ml-4"
									/>
								);
							},
							model: (scope: any) => {
								return (
									<el-link type="primary" onClick={() => clickBtn("details", scope.row)}>
										{scope.row.model}
									</el-link>
								);
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							operation: (scope: any) => {
								return (
									<>
										<el-link
											type="primary"
											link
											class="iconfont iconbx-file"
											onClick={() => {
												clickBtn("details", scope.row);
											}}
										>
											{proxy?.$t("rulelinks.operation.detail")}
										</el-link>
									</>
								);
							},
							empty: () => {
								return (
									<Empty
										showButton={buttonsList.value.find((menu: any) => menu.path == "add") ? true : false}
										class="text-left leading-6"
										subtitle={proxy?.$t("rulelinks.empty.subtitle")}
										btnText={proxy?.$t("rulelinks.empty.btn_text")}
										onAdd={() => clickBtn("add")}
									/>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
